package cn.itcast.order.configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author danDong
 * @date 2025-03-13 10:07:16
 */
@Component
public class ThreadManager {
    //创建线程池
    private ExecutorService executor = Executors.newCachedThreadPool();
    private Map<String, Future<?>> tasks = new HashMap<>();

    // 启动线程，key用于标识线程，以便后续停止
    public void startTask(String key, Callable<Void> task) {
        // 线程池给这个任务分配线程
        Future<?> future = executor.submit(task);
        tasks.put(key, future);
    }

    // 停止线程，通过key来识别
    public void stopTask(String key) {
        Future<?> future = tasks.get(key);
        if (future != null && !future.isDone()) {
            // 尝试中断任务，但仅当任务在等待、睡眠或尝试获取锁时才有效
            future.cancel(true);
            tasks.remove(key);
        }
    }

    // 关闭ExecutorService，释放资源
    public void shutdown() {
        executor.shutdown();
    }
}
